import { ACCurrentValueSubject } from './ACCurrentValueSubject';
import { ACCurrentValuePublisher } from './ACPublisher';

export function ACPublished(target: Object, propertyKey: string) {

  // 用来替换的getter
  const getter = function () {
    let value = this['__' + propertyKey + '__'];
    return value;
  }

  // 用来替换的setter
  const setter = function (newVal) {
    let value = this['__' + propertyKey + '__'];
    let oldVal = value;
    if (oldVal == newVal) {
      return;
    }

    this['__' + propertyKey + '__'] = newVal;

    let subject: ACCurrentValueSubject<any> = this['__ACSubject__'];
    subject?.sendValue(newVal);
  };

  // 替换属性，先删除原先的属性，再重新定义属性
  if (delete target[propertyKey]) {
    Object.defineProperty(target, propertyKey, {
      get: getter,
      set: setter,
      enumerable: false,
      configurable: true
    });
  }

  if (target['__ACSubject__'] === undefined) {
    target['__ACSubject__'] = null;
  }
}


class ACState {

  addObserver<T>(entity: Object, propertyKey: string): ACCurrentValuePublisher<T> | null {
    let subject: ACCurrentValueSubject<T> = entity['__ACSubject__'];
    if (subject === undefined) {
      const prototype = Object.getPrototypeOf(entity);
      console.error('0x09999' + '|ACCombine' + ' !!! 订阅失败：' + prototype.constructor.name + '.' + propertyKey + ' 请确认目标属性是否正确使用了 @ACStatePublished 注解!');
      return null;
    }

    if (subject == null) {
      let value = entity['__' + propertyKey + '__'];
      subject = new ACCurrentValueSubject<any>(value);
      entity['__ACSubject__'] = subject;
    }

    return subject.addPublisher();
  }
}

export default new ACState();
